<template>
    <div class="login-page">
      <div class="login-overlay"></div>
      <div class="login-container">
        <div class="logo-container">
          <i class="el-icon-plant"></i>
        </div>
        <h2>种花吧管理员登录</h2>
  
      <!-- 登录方式选择 -->
      <div class="login-mode-switcher">
        <button @click="toggleMode('password')" :class="{ active: mode === 'password' }">密码登录</button>
        <button @click="toggleMode('email')" :class="{ active: mode === 'email' }">邮箱验证码登录</button>
      </div>
  
      <!-- 密码登录表单 -->
      <el-form v-if="mode === 'password'" 
        :model="credentials" 
        :rules="passwordRules" 
        ref="passwordForm" 
        @submit.native.prevent="handlePasswordLogin"
        label-position="top"
        class="login-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="credentials.username" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input v-model="credentials.password" type="password" prefix-icon="el-icon-lock" show-password></el-input>
        </el-form-item>
        
        <div class="remember-forgot">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <a href="javascript:void(0)" @click="forgotPassword">忘记密码?</a>
        </div>
        
        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="loading" class="submit-btn">登录</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 邮箱验证码登录表单 -->
      <el-form v-else 
        :model="credentials" 
        :rules="emailRules" 
        ref="emailForm" 
        @submit.native.prevent="handleEmailLogin"
        label-position="top"
        class="login-form">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="credentials.email" prefix-icon="el-icon-message">
            <el-button slot="append" @click="sendVerificationCode" :disabled="cooldown > 0">
              {{ cooldown > 0 ? `${cooldown}秒后重试` : '发送验证码' }}
            </el-button>
          </el-input>
        </el-form-item>
        
        <el-form-item label="验证码" prop="verificationCode">
          <el-input v-model="credentials.verificationCode" prefix-icon="el-icon-key"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="loading" class="submit-btn">登录</el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>还没有管理员帐号？ <router-link to="/saveadmin">申请权限</router-link></p>
        <p><router-link to="/">返回首页</router-link></p>
      </div>
    </div>
    <div class="flower-decorations">
      <div class="flower flower-1"></div>
      <div class="flower flower-2"></div>
      <div class="flower flower-3"></div>
      <div class="flower flower-4"></div>
    </div>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        mode: 'password', // 默认为密码登录模式
        loading: false,
        rememberMe: false,
        cooldown: 0,
        cooldownTimer: null,
        credentials: {
          username: '',
          password: '',
          email: '',
          verificationCode: ''
        },
        passwordRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
          ]
        },
        emailRules: {
          email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
          ],
          verificationCode: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            { min: 4, max: 6, message: '验证码长度不正确', trigger: 'blur' }
          ]
        }
      };
    },
    beforeDestroy() {
      if (this.cooldownTimer) {
        clearInterval(this.cooldownTimer);
      }
    },
    methods: {
      toggleMode(mode) {
        this.mode = mode;
        // 清空表单数据
        this.credentials = {
          username: '',
          password: '',
          email: '',
          verificationCode: ''
        };
      },
      handlePasswordLogin() {
        this.$refs.passwordForm.validate(valid => {
          if (valid) {
            this.loading = true;
            
            // 根据后端接口格式构造请求数据
            const loginData = {
              username: this.credentials.username,
              password: this.credentials.password
            };
            
            this.request.post("/admins/login", loginData).then(res => {
              this.loading = false;
              if (res.code === 1) {
                // 如果选择记住我，将登录凭证保存到 localStorage
                if (this.rememberMe) {
                  localStorage.setItem('adminToken', res.data);
                  localStorage.setItem('adminUsername', this.credentials.username);
                }
                // 否则存储在 sessionStorage
                sessionStorage.setItem('adminToken', res.data);
                sessionStorage.setItem('adminUsername', this.credentials.username);
                
                this.$message.success("登录成功");
                
                // 跳转到管理员首页
                this.$router.push("/adminhome");
              } else {
                this.$message.error(res.msg || "用户名或密码错误");
              }
            }).catch(error => {
              this.loading = false;
              console.error("登录错误:", error);
              this.$message.error("登录出错，请稍后重试");
            });
          }
        });
      },
      handleEmailLogin() {
        this.$refs.emailForm.validate(valid => {
          if (valid) {
            this.loading = true;
            const loginData = {
              email: this.credentials.email,
              code: this.credentials.verificationCode
            };
            
            this.request.post("/admins/loginByEmail", loginData).then(res => {
              this.loading = false;
              if (res.code === 1) {
                // 存储token
                if (this.rememberMe) {
                  localStorage.setItem('adminToken', res.data);
                  localStorage.setItem('adminEmail', this.credentials.email);
                }
                sessionStorage.setItem('adminToken', res.data);
                sessionStorage.setItem('adminEmail', this.credentials.email);
                
                this.$message.success("登录成功");
                this.$router.push("/adminhome");
              } else {
                this.$message.error(res.msg || "登录失败，请检查邮箱和验证码");
              }
            }).catch(error => {
              this.loading = false;
              console.error("登录错误:", error);
              this.$message.error("登录出错，请稍后重试");
            });
          }
        });
      },
      sendVerificationCode() {
        this.$refs.emailForm.validateField('email', (errorMessage) => {
          if (errorMessage) {
            return; // 如果邮箱验证不通过，不发送验证码
          }
          
          this.cooldown = 60; // 设置冷却时间为60秒
          this.cooldownTimer = setInterval(() => {
            this.cooldown--;
            if (this.cooldown <= 0) {
              clearInterval(this.cooldownTimer);
            }
          }, 1000);
          
          this.request.post("/admins/sendVerificationCode", { 
            email: this.credentials.email 
          }).then(res => {
            if (res.code === 1) {
              this.$message.success("验证码已发送，请查收邮箱");
            } else {
              this.$message.error(res.msg || "验证码发送失败");
            }
          }).catch(error => {
            console.error("发送验证码错误:", error);
            this.$message.error("验证码发送出错，请稍后重试");
          });
        });
      },
      forgotPassword() {
        this.$prompt('请输入您的管理员邮箱', '找回密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          inputErrorMessage: '邮箱格式不正确'
        }).then(({ value }) => {
          this.request.post("/admins/resetPassword", { email: value })
            .then(res => {
              if (res.code === 1) {
                this.$message.success("重置密码链接已发送到您的邮箱");
              } else {
                this.$message.error(res.msg || "发送重置密码链接失败");
              }
            })
            .catch(error => {
              console.error("重置密码错误:", error);
              this.$message.error("重置密码请求出错，请稍后重试");
            });
        }).catch(() => {
          this.$message.info('已取消操作');
        });
      }
    }
  };
  </script>
  
  <style scoped>
  .login-page{
    background-image: url('~@/assets/images/login.jpg'); /* 使用 Webpack 解析路径 */
    background-size: cover; /* 覆盖整个区域 */
    background-position: center; /* 图片居中 */
    background-repeat: no-repeat; /* 防止图片重复 */
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;
  }
  
  .login-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(152, 207, 195, 0.7), rgba(86, 181, 184, 0.7));
    z-index: 1;
  }
  
  .login-container {
    width: 380px;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
    padding: 35px;
    position: relative;
    z-index: 2;
    animation: fadeIn 0.8s ease-out;
  }
  
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
  }

  .logo-container {
    text-align: center;
    margin-bottom: 15px;
  }
  
  .logo-container i {
    font-size: 40px;
    color: #67C23A;
    background: rgba(103, 194, 58, 0.1);
    padding: 15px;
    border-radius: 50%;
  }
  
  h2 {
    text-align: center;
    margin-bottom: 25px;
    color: #3c9566;
    font-size: 24px;
    font-weight: 600;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }
  
  .login-mode-switcher {
    display: flex;
    justify-content: space-around;
    margin-bottom: 25px;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #dcdfe6;
  }
  
  .login-mode-switcher button {
    flex: 1;
    background-color: #f5f7fa;
    border: none;
    padding: 12px 15px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    color: #606266;
  }
  
  .login-mode-switcher button.active {
    background-color: #67C23A;
    color: white;
    font-weight: 500;
  }
  
  .login-mode-switcher button:hover:not(.active) {
    background-color: #e7f5e0;
  }
  
  .login-form {
    margin-bottom: 20px;
  }
  
  .remember-forgot {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .remember-forgot a {
    color: #67C23A;
    text-decoration: none;
    font-size: 14px;
  }
  
  .remember-forgot a:hover {
    text-decoration: underline;
  }
  
  .submit-btn {
    width: 100%;
    padding: 12px;
    font-size: 16px;
    background-color: #67C23A;
    border-color: #67C23A;
    transition: all 0.3s;
  }
  
  .submit-btn:hover {
    background-color: #5daf33;
    border-color: #5daf33;
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(103, 194, 58, 0.3);
  }
  
  .login-footer {
    text-align: center;
    margin-top: 20px;
    font-size: 14px;
    color: #606266;
  }
  
  .login-footer a {
    color: #67C23A;
    text-decoration: none;
  }
  
  .login-footer a:hover {
    text-decoration: underline;
  }
  
  .login-footer p {
    margin: 8px 0;
  }

  .flower-decorations {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1;
    pointer-events: none;
  }

  .flower {
    position: absolute;
    width: 60px;
    height: 60px;
    background-size: contain;
    background-repeat: no-repeat;
    opacity: 0.7;
  }

  .flower-1 {
    top: 10%;
    left: 10%;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%2367C23A"><path d="M12,2L8,6H11V9.43C9.97,9.89 9.17,10.69 8.71,11.73C8.5,11.92 8.5,12.2 8.5,12.5C8.5,13.05 8.95,13.5 9.5,13.5C10.05,13.5 10.5,13.05 10.5,12.5V12C10.5,11.45 10.95,11 11.5,11C12.05,11 12.5,11.45 12.5,12V12.5C12.5,13.05 12.95,13.5 13.5,13.5C14.05,13.5 14.5,13.05 14.5,12.5C14.5,12.23 14.5,11.93 14.29,11.74C13.83,10.7 13.03,9.89 12,9.43V6H16L12,2M6,19C6,20.1 10.66,21 12,21C13.34,21 18,20.1 18,19C18,17.9 14.34,15 12,15C9.66,15 6,17.9 6,19Z" /></svg>');
    animation: floatAnimation 10s infinite ease-in-out;
  }

  .flower-2 {
    top: 15%;
    right: 15%;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23E6A23C"><path d="M12,2L8,6H11V9.43C9.97,9.89 9.17,10.69 8.71,11.73C8.5,11.92 8.5,12.2 8.5,12.5C8.5,13.05 8.95,13.5 9.5,13.5C10.05,13.5 10.5,13.05 10.5,12.5V12C10.5,11.45 10.95,11 11.5,11C12.05,11 12.5,11.45 12.5,12V12.5C12.5,13.05 12.95,13.5 13.5,13.5C14.05,13.5 14.5,13.05 14.5,12.5C14.5,12.23 14.5,11.93 14.29,11.74C13.83,10.7 13.03,9.89 12,9.43V6H16L12,2M6,19C6,20.1 10.66,21 12,21C13.34,21 18,20.1 18,19C18,17.9 14.34,15 12,15C9.66,15 6,17.9 6,19Z" /></svg>');
    animation: floatAnimation 15s infinite ease-in-out reverse;
  }

  .flower-3 {
    bottom: 20%;
    left: 20%;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23F56C6C"><path d="M12,2L8,6H11V9.43C9.97,9.89 9.17,10.69 8.71,11.73C8.5,11.92 8.5,12.2 8.5,12.5C8.5,13.05 8.95,13.5 9.5,13.5C10.05,13.5 10.5,13.05 10.5,12.5V12C10.5,11.45 10.95,11 11.5,11C12.05,11 12.5,11.45 12.5,12V12.5C12.5,13.05 12.95,13.5 13.5,13.5C14.05,13.5 14.5,13.05 14.5,12.5C14.5,12.23 14.5,11.93 14.29,11.74C13.83,10.7 13.03,9.89 12,9.43V6H16L12,2M6,19C6,20.1 10.66,21 12,21C13.34,21 18,20.1 18,19C18,17.9 14.34,15 12,15C9.66,15 6,17.9 6,19Z" /></svg>');
    animation: floatAnimation 12s infinite ease-in-out;
  }

  .flower-4 {
    bottom: 15%;
    right: 10%;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23409EFF"><path d="M12,2L8,6H11V9.43C9.97,9.89 9.17,10.69 8.71,11.73C8.5,11.92 8.5,12.2 8.5,12.5C8.5,13.05 8.95,13.5 9.5,13.5C10.05,13.5 10.5,13.05 10.5,12.5V12C10.5,11.45 10.95,11 11.5,11C12.05,11 12.5,11.45 12.5,12V12.5C12.5,13.05 12.95,13.5 13.5,13.5C14.05,13.5 14.5,13.05 14.5,12.5C14.5,12.23 14.5,11.93 14.29,11.74C13.83,10.7 13.03,9.89 12,9.43V6H16L12,2M6,19C6,20.1 10.66,21 12,21C13.34,21 18,20.1 18,19C18,17.9 14.34,15 12,15C9.66,15 6,17.9 6,19Z" /></svg>');
    animation: floatAnimation 18s infinite ease-in-out reverse;
  }

  @keyframes floatAnimation {
    0% { transform: translate(0, 0) rotate(0deg); }
    25% { transform: translate(-10px, 10px) rotate(5deg); }
    50% { transform: translate(0, 20px) rotate(0deg); }
    75% { transform: translate(10px, 10px) rotate(-5deg); }
    100% { transform: translate(0, 0) rotate(0deg); }
  }

  @media (max-width: 768px) {
    .login-container {
      width: 90%;
      max-width: 380px;
      padding: 25px;
    }
  }
  </style>